import os
import tempfile
from datetime import datetime

from flask import request, current_app, jsonify
from flask_classy import FlaskView, route

from ..schema.error import FILE_TYPE_ERROR, IMAGE_TYPE_ERROR
from ..schema.resp import resource_schema
from ..services.resource import ResourceService
import shortuuid


class ResourcesView(FlaskView):

    @route('/upload_files', methods=['POST'])
    def upload_img(self):
        file = request.files['file']
        UPLOAD_FOLDER = current_app.config.get('UPLOAD_FOLDER', tempfile.gettempdir())
        prefix = file.filename.rsplit('.', 1)[1]
        image_file = ['jpeg','png']
        doc_file = ['txt','csv']
        if prefix in image_file:
            resize = request.form.get('resize')
            thumb = request.form.get('thumb')
            response = request.form.get('response_format', None)
            prefix = request.form.get('prefix', '')
            if resize and resize.find('x') != -1:
                resize = tuple(resize.split('x'))

            if thumb and thumb.find('x') != -1:
                thumb = tuple(thumb.split('x'))

            file_list = []

            file_dir = os.path.join(UPLOAD_FOLDER, prefix)
            if not os.path.exists(file_dir):
                os.makedirs(file_dir)
            for fn in request.files:
                f = request.files[fn]
                resource_id = shortuuid.uuid()

                origin_file_name = f.filename

                file_path = '{file_dir}/{file_name}'.format(file_dir=file_dir, file_name=resource_id)
                thumb_path = None

                mimetype = f.mimetype
                content_type = f.content_type
                content_length = f.content_length or -1

                f.save(file_path)
                from extensions import file_store

                if resize or thumb:
                    from PIL import Image

                    with Image.open(file_path) as image:
                        if resize:
                            real_image = image.resize((int(resize[0]), int(resize[1])), Image.ANTIALIAS)
                            file_name = create_file_name(prefix,
                                                         'resize_{}_{}x{}.jpg'.format(resource_id, resize[0],
                                                                                      resize[1]))

                            file_path = os.path.join(UPLOAD_FOLDER, file_name)
                            real_image.save(file_path)
                            file_store.put_file(file_name, file_path)

                            file_path = file_name
                            # file_store.put_stream()
                            print(file_store.url_for(file_path))

                        if thumb:
                            thumb_image = image.copy()
                            file_name = 'thumb_{}_{}x{}.jpg'.format(file_name, thumb[0], thumb[1])
                            thumb_path = os.path.join(UPLOAD_FOLDER, file_name)
                            thumb_image.thumbnail((thumb[0], thumb[1]))
                            thumb_image.save(os.path.join(UPLOAD_FOLDER, file_name))
                            file_store.put_file(file_name, thumb_path, )

                            thumb_path = file_name
                else:
                    file_name = shortuuid.uuid()
                    file_store.put_file(file_name, file_path)
                    file_path = file_name
                    if not thumb_path:
                        thumb_path = file_path

                file_list.append(ResourceService.create(
                    id=resource_id,
                    mime_type=mimetype,
                    origin_file_name=origin_file_name,
                    type=file_store.type(),
                    # content_type=content_type,
                    size=content_length,
                    path=file_path,
                    thumb_path=thumb_path if thumb_path else file_path

                ))
                return resource_schema.jsonify(file_list[0])
            else:
                return IMAGE_TYPE_ERROR.jsonify()
        if prefix in doc_file:
            date = datetime.now().strftime('%Y%m%d')
            key_doc_folder = os.path.exists('key_doc' + '/' + date)
            if not key_doc_folder:
                os.makedirs('key_doc' + '/' + date)
            file_list = []
            for fn in request.files:
                file = request.files[fn]
                time_folder_name = datetime.now().strftime('%H%M%S%f')
                os.makedirs('key_doc' + '/' + date + '/' + time_folder_name)
                file_path = '{key_doc}/{date}/{time_folder_name}'.format(key_doc='key_doc', date=date,
                                                                         time_folder_name=time_folder_name)
                file.save(os.path.join(file_path, file.filename))
                resource_id = shortuuid.uuid()
                mimetype = file.mimetype
                origin_file_name = file.filename
                content_length = len(file.filename) or -1
                file_list.append(ResourceService.create(
                    id=resource_id,
                    mime_type=mimetype,
                    origin_file_name=origin_file_name,
                    type='local_file',
                    size=content_length,
                    path=file_path + '/' + file.filename,
                    thumb_path=file_path + '/' + file.filename
                ))
            return jsonify(resource_id=resource_id,type='local_file',
                           path=file_path + '/' + file.filename,
                           thumb_path=file_path + '/' + file.filename,
                           mime_type=mimetype,
                           )
        else:
            return FILE_TYPE_ERROR.jsonify()


def create_file_name(prefix, file_name):
    file_name = '{}'.format(file_name) if not prefix else '{}/{}'.format(prefix, file_name)
    return file_name